// create_index_directly.js - 直接使用HNSWLib API创建索引
require('dotenv').config();
const { HNSWLib } = require("@langchain/community/vectorstores/hnswlib");
const { Embeddings } = require("@langchain/core/embeddings");
const path = require('path');
const fs = require('fs');

// 自定义嵌入类，使用固定向量
class FixedEmbeddings extends Embeddings {
    constructor(fields) {
        super(fields || {});
    }

    async embedDocuments(texts) {
        const embeddings = [];
        for (const text of texts) {
            const embedding = await this.embedQuery(text);
            embeddings.push(embedding);
        }
        return embeddings;
    }

    async embedQuery(text) {
        // 返回固定向量
        return Array.from({ length: 1536 }, () => 0.1);
    }
}

const VECTOR_STORE_PATH = path.join(__dirname, 'vector_store');
const embeddings = new FixedEmbeddings();

async function createIndexDirectly() {
    try {
        console.log("开始直接创建HNSW索引...");
        
        // 确保目录存在
        if (!fs.existsSync(VECTOR_STORE_PATH)) {
            fs.mkdirSync(VECTOR_STORE_PATH, { recursive: true });
            console.log("创建向量存储目录");
        }
        
        // 创建一个空的向量存储
        console.log("创建空的向量存储...");
        const vectorStore = new HNSWLib(embeddings, {
            space: 'cosine',
            numDimensions: 1536,
        });
        
        // 添加一些测试文档
        console.log("添加测试文档...");
        const docs = [
            { pageContent: "React Hooks是React 16.8版本引入的新特性", metadata: { source: "react" } },
            { pageContent: "Vue Composition API是Vue 3.0中引入的新特性", metadata: { source: "vue" } },
            { pageContent: "JavaScript异步编程是JavaScript中非常重要的一部分", metadata: { source: "javascript" } }
        ];
        
        await vectorStore.addDocuments(docs);
        
        // 保存向量存储
        console.log("保存向量存储...");
        await vectorStore.save(VECTOR_STORE_PATH);
        console.log("向量存储保存成功");
        
        // 验证向量存储
        console.log("验证向量存储...");
        const loadedVectorStore = await HNSWLib.load(VECTOR_STORE_PATH, embeddings);
        const results = await loadedVectorStore.similaritySearch("React Hooks", 2);
        
        console.log("搜索结果:");
        results.forEach((result, index) => {
            console.log(`结果 ${index + 1}: ${result.pageContent.substring(0, 100)}...`);
        });
        
        // 检查文件大小
        console.log("\n检查生成的文件:");
        const files = fs.readdirSync(VECTOR_STORE_PATH);
        for (const file of files) {
            const filePath = path.join(VECTOR_STORE_PATH, file);
            const stats = fs.statSync(filePath);
            console.log(`${file}: ${stats.size} 字节`);
        }
        
        console.log("HNSW索引创建完成！");
        
    } catch (error) {
        console.error("创建HNSW索引失败:", error);
    }
}

// 运行创建
createIndexDirectly();